package com.mornd.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.mornd.gulimall.apis.search.to.SkuEsModel;
import com.mornd.gulimall.search.constant.EsConstant;
import com.mornd.gulimall.search.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

import static com.mornd.gulimall.search.config.ElasticsearchConfig.COMMON_OPTIONS;

/**
 * @author: mornd
 * @dateTime: 2023/8/9 - 18:04
 */

@Slf4j
@Service
public class ProductServiceImpl implements ProductService {
    @Resource
    private RestHighLevelClient restHighLevelClient;

    /**
     * 上架商品
     *
     * @param skuEsModels
     */
    @Override
    public boolean statusUp(List<SkuEsModel> skuEsModels) {
        // 1、创建 product 索引库，定义文档数据类型(resources/es/product-mapping.txt)

        /*
            keyword 类型不会进行全文检索，而是精确匹配
            text 全文检索，保存数据的时候进行分词，检索的时候按照分词进行匹配
         */

        // 2、批量保存
        BulkRequest bulkRequest = new BulkRequest();

        for (SkuEsModel skuEs : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            // 设置 id
            indexRequest.id(skuEs.getSkuId().toString());
            String json = JSON.toJSONString(skuEs);
            indexRequest.source(json, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }

        try {
            log.info("开始上架商品，count：{}", skuEsModels.size());
            BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, COMMON_OPTIONS);

            log.info("上架完成，是否包含错误：{}", bulkResponse.hasFailures());

//            BulkItemResponse[] items = bulkResponse.getItems();
//            for (BulkItemResponse item : items) {
//                String id = item.getId();
//                String failureMessage = item.getFailureMessage();
//                // ...
//            }

            // todo 商品上架异常
            return !bulkResponse.hasFailures();

            // 3、查看结果 GET product/_search
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
